<script lang="ts" setup>
import { ref } from "vue";
// 消息
const message = ref<string>("");

// 输入内容
const inpValue = ref<string>("");

const fetchData = async () => {
  if (!inpValue.value.length) return;
  // 参数模型
  const model = {
    model: "gpt-3.5-turbo",
    messages: [
      // { role: "user", content: inpValue.value },
      { role: "system", content: inpValue.value },
      // { role: "assistant", content: inpValue.value },
    ],
    stream: true,
  };
  const response = await fetch("https://api.chatanywhere.com.cn/v1/chat/completions", {
    method: "POST",
    headers: {
      Authorization: "Bearer sk-8s95trzUJbxnLcUr8SWFAOuMAUTc1PvAKz2Oaa9TtVifkB7u",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(model),
  });

  const reader = response.body!.getReader();
  const decoder = new TextDecoder("utf-8");

  while (true) {
    var { value, done } = await reader.read();
    if (done) break;
    const chunk = decoder.decode(value, { stream: true });
    const lines = chunk.split("\n\n");
    lines.forEach((line) => {
      if (line !== "" && line !== "data: [DONE]") {
        const lineObj = JSON.parse(line.slice(6));
        console.log("🚀 ~ lines.forEach ~ lineObj:", lineObj);
        if (lineObj.choices[0].delta.content === undefined) return;
        message.value += lineObj.choices[0].delta.content;
      } else {
        const index = lines.findIndex((item) => item === line);
        lines.splice(index, 1);
      }
    });
  }
};
</script>

<template>
  <div class="container">
    <div>chatGPT free api</div>
    <div>请输入消息：</div>
    <div class="inp">
      <input class="input" type="text" v-model="inpValue" />
      <div class="button cursor-pointer" @click="fetchData()">发送</div>
    </div>
    <br />
    <div>返回消息:</div>
    <div>{{ message }}</div>
  </div>
</template>

<style lang="css" scoped>
.container {
  width: 100%;
  .inp {
    display: flex;
    gap: 10px;
  }
  .input {
    border: 1px solid black;
    border-radius: 5px;
  }
  .button {
    border: 1px solid black;
    padding: 5px 10px;
    border-radius: 5px;
  }
}
</style>
